package com.liu.sx.service;

import com.liu.sx.common.util.IdWorker;
import com.liu.sx.dao.VoltageDao;
import com.liu.sx.entity.Voltage;
import com.liu.sx.pojo.BW;
import com.liu.sx.util.ArrayUtils;
import com.liu.sx.util.BCD2String;
import com.liu.sx.util.BwUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Transactional
@Slf4j
public class VoltageService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private VoltageDao voltageDao;


    public void insert(BW bw){

        Voltage v1 = getVoltageFromBW(bw);

        v1.setBwTime(new Date());

        voltageDao.save(v1);
    }

    private Voltage getVoltageFromBW(BW bw) {
        byte[] msg = BwUtil.Object2byte(bw);

        int voltage = (msg[msg.length-6]&0xff);
        int signNum = msg[msg.length-3];

        String low=Integer.toBinaryString(msg[msg.length-5]&0xff);
        log.info("灯管数值："+(msg[msg.length-5]&0xff));
        log.info("灯管状态低位："+low);
        while (low.length()<8){
            low="0"+low;
        }

        String hight=Integer.toBinaryString(msg[msg.length-4]);
      if(hight.equals("0")){
          hight="00";
        }else if(hight.equals("1")){
          hight="01";
      }
        log.info("灯管状态高位："+hight);
      String  ls=hight+low;


        System.out.println("===========voltage========="+voltage);
        // 电压 计算公式：接收到的值，（n+300 ）*10
        voltage = (voltage+300 )*10;

        byte []  rq = Arrays.copyOfRange(msg,10,13);
        byte [] count_ =Arrays.copyOfRange(msg,13,13+96);
        System.out.println("数组长度"+count_.length);

        String sbrq = BCD2String.bcd2Str(rq);
        Date date =null;
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        try {
             date = df.parse("20"+sbrq);
        } catch (ParseException e) {
            e.printStackTrace();
        }



        Voltage  v1 = new Voltage();

        v1.setId(idWorker.nextId()+"");
        v1.setRq(date);
        v1.setVolt(voltage);
        v1.setAddress(bw.getAddress());
        v1.setCount(ArrayUtils.sumByte(count_));
   log.info("灯管状态："+ls);
        v1.setLightState(ls);
        v1.setSignNum(signNum);





        return v1;
    }

    public Page<Voltage> findByQuery(int num, int rows, String query) {

        Pageable  pageable = PageRequest.of(num-1,rows, Sort.Direction.DESC,"bwTime");
        return voltageDao.findAll(query,pageable);


    }


    public List<Voltage> findByAdress(String adress) {

        return voltageDao.findByAddress(adress);
    }
}
